import re
import wsgiref.handlers
import SecretKey
import logging
import sys
from HTMLParser import HTMLParser
from google.appengine.api import urlfetch
from google.appengine.ext import webapp

class GtalkStatusParser(HTMLParser):
  """Parse the content of google talk chatback badge to get the status"""

  __status__=''
  def __getStatus__(self, tag, attrs):
    if tag == 'img' and ('id','b') in attrs:
      attrs_dict=dict(attrs)
      self.__status__ = re.sub('/.*/(.*)\.gif', '\\1', attrs_dict['src'])
  def handle_starttag(self, tag, attrs):
    self.__getStatus__(tag,attrs)
  def handle_startendtag(self, tag, attrs):
    self.__getStatus__(tag, attrs)
  def status(self):
    return self.__status__

# On Google App Engine, if you want to connect to external server,
# you have to use URL Fetch API provided by google instead of others
# in standard libraries, such as urllib2.
# Google App Engine SDK v1.0.2 has a bug about making http requests by
# GET method, which discards the querystring appended to URL. See below
# website for reference and solutions:
# http://code.google.com/p/googleappengine/issues/detail?id=341

class getStatusPage(webapp.RequestHandler):
  URL="http://www.google.com/talk/service/badge/Show"
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    try:
      tk = self.request.get('tk')
      auth = self.request.get('auth')

      # Validation of parameters
      if re.search("[^0-9a-zA-Z]",tk):
        raise ValueError
      if not SecretKey.validate(tk, auth):
        raise ValueError

      parser = GtalkStatusParser()
      # Create the google talk badge url in order to parse the online status of the user
      gtalkBadgeURL = self.URL + '?tk=' + tk
      logging.debug("Sending request to gtalk. URL=%s", gtalkBadgeURL)

      parser.feed(urlfetch.fetch(gtalkBadgeURL).content)
      userStatus = parser.status()
      self.response.out.write(userStatus + '\n')
      logging.debug("getStatusPage(): User status=%s, tk=%s", userStatus, tk)
    except (TypeError, ValueError):
      logging.debug("Exception occured: %s", sys.exc_info())
      self.response.out.write("Invalid inputs\n")

def main():
  mapping=[('/getStatus',getStatusPage)]
  application = webapp.WSGIApplication(mapping)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main() 
